import * as Api from '@/api/user'
import authority from '@/utils/authority'

const state = {
  user: authority.get() || {},
  client_id: '',
}

const mutations = {
  SET_USER(state, payload = {}) {
    Object.assign(state, payload)
  },
}

const actions = {
  async login({ commit }, screen_key) {
    if (!screen_key) return
    const cache = authority.get() || {}
    if (cache.screen_key === screen_key) return
    const res = await Api.login(screen_key)
    res.screen_key = screen_key
    commit('SET_USER', { user: res })
    authority.set(res)
  },
}

export default {
  state,
  mutations,
  actions,
}
